// ignore_for_file: always_specify_types

import 'package:flutter/material.dart';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:medical_pro_flutter/entity/User.dart';
import 'package:path/path.dart';
import '../../api/Api.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'dart:convert';
import 'tabs.dart';

class ShowCropedImagePage extends StatelessWidget {
  File f;
  static BuildContext? ctxt;
  ShowCropedImagePage(this.f);

  @override
  Widget build(BuildContext context) {
    // print('进来了');
    ctxt = context;
    return Container(
        child: Column(
      children: <Widget>[
        Expanded(
          child: Image.file(f),
        ),
        Container(
            padding: const EdgeInsets.only(top: 20.0),
            alignment: AlignmentDirectional.center,
            child: ElevatedButton(
              child: Text('确认上传'),
              onPressed: _submitCropedImage,
            ))
      ],
    ));
  }

  _submitCropedImage() async {
    String url = API.BASE_URL + API.HEAD_IMAGE + User.job_num + '/';
    print('请求的url：$url');

    Response response;

    try {
      var dio = Dio();
      print('图片路径：${f.path}');
      var formData = FormData.fromMap({
        'photos': [
          MultipartFile.fromFileSync(f.path,
              filename: User.job_num + '_headimage.jpg'),
        ]
      });
      response = await dio.post(url, data: formData);
      print('code:${response.statusCode}');

      //拿到返回数据，先实例化更改User，再同步到本地数据库
      if (response.statusCode == 200) {
        Map<String, dynamic> changedInfo = json.decode(response.data);
        // Map<String, dynamic> changedInfo =
        //     Map<String, dynamic>.from(response.data);

        User.head_image = changedInfo['head_image'];
        User.updateToLocalDB();

        Fluttertoast.showToast(
          msg: '头像修改成功',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          timeInSecForIosWeb: 3,
          backgroundColor: Colors.white,
          textColor: Colors.black,
          fontSize: 16.0,
        );

        Navigator.pop(ctxt!);
        Navigator.pop(ctxt!);
      }
    } catch (e) {
      print(e.toString());
      Navigator.pop(ctxt!);

      Fluttertoast.showToast(
        msg: '头像修改失败',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIosWeb: 3,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0,
      );
    }
  }
}
